package org.example.domain.user_raffle.service.algorithm.Impl;

import org.apache.commons.lang3.tuple.Pair;
import org.example.domain.user_raffle.service.algorithm.IRaffleAlgorithm;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

/**
 * @author lxc18
 * @date 2025/3/29 21:34
 * @description RaffleAlgorithmON
 */
@Component
public class RaffleAlgorithmON implements IRaffleAlgorithm {
    @Override
    public Long doRaffle(List<Pair<Long, BigDecimal>> prizeIds) {
        if (prizeIds == null || prizeIds.isEmpty()) {
            return null;
        }

        // 计算总概率
        BigDecimal total = BigDecimal.ZERO;
        for (Pair<Long, BigDecimal> pair : prizeIds) {
            total = total.add(pair.getValue());
        }
        if (total.compareTo(BigDecimal.ZERO) == 0) {
            return null; // 所有概率都为0，无法抽奖
        }

        // 生成一个[0, total)之间的随机数
        Random random = new Random();
        double randomDouble = random.nextDouble() * total.doubleValue();
        BigDecimal randomValue = BigDecimal.valueOf(randomDouble);

        // 累积概率查找
        BigDecimal accumulated = BigDecimal.ZERO;
        for (Pair<Long, BigDecimal> pair : prizeIds) {
            accumulated = accumulated.add(pair.getValue());
            if (accumulated.compareTo(randomValue) > 0) {
                return pair.getKey();
            }
        }

        // 由于浮点数精度问题，返回最后一个元素
        return prizeIds.get(prizeIds.size() - 1).getKey();
    }
}
